package com.example.ercmssystem2.service.impl;

import com.example.ercmssystem2.entity.Event;
import com.example.ercmssystem2.entity.EventResource;
import com.example.ercmssystem2.entity.EventResponse;
import com.example.ercmssystem2.entity.EventType;
import com.example.ercmssystem2.entity.User;
import com.example.ercmssystem2.entity.Resource;
import com.example.ercmssystem2.repository.*;
import com.example.ercmssystem2.repository.EventResponseRepository;
import com.example.ercmssystem2.service.EventService;
import com.example.ercmssystem2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.time.format.DateTimeFormatter;

@Service
@Transactional
public class EventServiceImpl implements EventService {

    @Autowired
    private EventRepository eventRepository;

    @Autowired
    private EventResponseRepository eventResponseRepository;


    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ResourceRepository resourceRepository;

    @Autowired
    private EventResourceRepository eventResourceRepository;

    @Autowired
    private UserService userService;

    @Override
    public Event saveEvent(Event event) {
        if (event.getId() == null) {
            event.setCreatedAt(LocalDateTime.now());
            event.setUpdatedAt(LocalDateTime.now());
            event.setStatus("PENDING");
            event.setProgressPercentage(0);
            event.setEscalationLevel(0);
            
            // 设置终端用户相关字段的默认值
            if (event.getSupportRequested() == null) {
                event.setSupportRequested(false);
            }
            
            // 坐标字段初始创建时可以为null，不需要设置默认值
            // 终端用户接受事件后会通过updateLocation方法设置坐标
        } else {
            event.setUpdatedAt(LocalDateTime.now());
        }
        
        Event savedEvent = eventRepository.save(event);
        
        return savedEvent;
    }

    @Override
    public Event findById(Long id) {
        return eventRepository.findById(id).orElse(null);
    }

    @Override
    public List<Event> findAllEvents() {
        return eventRepository.findAll();
    }

    @Override
    public List<Event> findByStatus(String status) {
        return eventRepository.findByStatus(status);
    }

    @Override
    public List<Event> findByEventType(EventType eventType) {
        return eventRepository.findByEventType(eventType);
    }

    @Override
    public List<Event> findByReporter(User reporter) {
        return eventRepository.findByReporter(reporter);
    }

    @Override
    public List<Event> findByHandler(User handler) {
        return eventRepository.findByHandler(handler);
    }

    @Override
    public List<Event> findEventsInTimeRange(LocalDateTime start, LocalDateTime end) {
        return eventRepository.findEventsInTimeRange(start, end);
    }

    @Override
    public List<Event> findByStatusAndPriority(String status, String priority) {
        return eventRepository.findByStatusAndPriority(status, priority);
    }

    @Override
    public void deleteEvent(Long id) {
        Event event = findById(id);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        try {
            // 先释放处理人
            if (event.getHandler() != null) {
                userService.updateUserStatus(event.getHandler().getId(), "AVAILABLE");
            }
            
            // 先释放资源
            releaseResourcesForEvent(id);
            
            // 删除事件（由于设置了级联删除，相关的event_resource和event_responses记录会自动删除）
            eventRepository.deleteById(id);
        } catch (Exception e) {
            System.err.println("删除事件失败: " + e.getMessage());
            throw new RuntimeException("删除事件失败: " + e.getMessage());
        }
    }

    @Override
    public Event updateEventStatus(Long id, String status) {
        Event event = findById(id);
        if (event != null) {
            event.setStatus(status);
            event.setUpdatedAt(LocalDateTime.now());
            
            // 如果状态为已解决或已关闭，自动释放处理人
            if ("RESOLVED".equals(status) || "CLOSED".equals(status)) {
                if (event.getHandler() != null) {
                    userService.updateUserStatus(event.getHandler().getId(), "AVAILABLE");
                }
                event.setResolutionTime(LocalDateTime.now());
                releaseResourcesForEvent(id);
            }
            
            return eventRepository.save(event);
        }
        return null;
    }

    // 自动释放事件关联的资源（只更新状态，保留记录）
    private void releaseResourcesForEvent(Long eventId) {
        try {
            List<Long> resourceIds = eventResourceRepository.findResourceIdsByEventId(eventId);
            if (resourceIds != null && !resourceIds.isEmpty()) {
                // 更新资源状态为可用
                List<Resource> resources = resourceRepository.findAllById(resourceIds);
                for (Resource resource : resources) {
                    resource.setStatus("AVAILABLE");
                }
                resourceRepository.saveAll(resources);
                
                // 更新事件资源关联记录的状态为已完成
                List<EventResource> eventResources = eventResourceRepository.findByEventId(eventId);
                if (eventResources != null && !eventResources.isEmpty()) {
                    LocalDateTime completionTime = LocalDateTime.now();
                    for (EventResource er : eventResources) {
                        er.setStatus("COMPLETED");
                        er.setNotes("事件完成，资源已释放 - " + completionTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    }
                    eventResourceRepository.saveAll(eventResources);
                }
            }
        } catch (Exception e) {
            System.err.println("释放事件资源失败: " + e.getMessage());
            // 不抛出异常，避免影响事件状态更新
        }
    }

    @Override
    public Event assignHandler(Long id, User handler) {
        Event event = findById(id);
        if (event != null) {
            // 如果之前有处理人，将其状态设置为AVAILABLE
            if (event.getHandler() != null) {
                userService.updateUserStatus(event.getHandler().getId(), "AVAILABLE");
            }
            
            event.setHandler(handler);
            event.setStatus("ASSIGNED");
            event.setAssignedTime(LocalDateTime.now());
            event.setUpdatedAt(LocalDateTime.now());
            
            // 将新处理人的状态设置为BUSY
            if (handler != null) {
                userService.updateUserStatus(handler.getId(), "BUSY");
            }
            
            return eventRepository.save(event);
        }
        return null;
    }

    // 额外的方法
    public Event createEvent(Event event, Long createdBy) {
        event.setCreatedAt(LocalDateTime.now());
        event.setUpdatedAt(LocalDateTime.now());
        event.setCreatedBy(createdBy);
        event.setStatus("PENDING");
        event.setProgressPercentage(0);
        event.setEscalationLevel(0);
        
        Event savedEvent = eventRepository.save(event);
        

        
        return savedEvent;
    }

    public Event updateEvent(Long id, Event event) {
        Event existingEvent = findById(id);
        if (existingEvent == null) {
            throw new RuntimeException("事件不存在");
        }
        
        existingEvent.setTitle(event.getTitle());
        existingEvent.setDescription(event.getDescription());
        existingEvent.setLocation(event.getLocation());
        existingEvent.setPriority(event.getPriority());
        existingEvent.setSeverity(event.getSeverity());
        existingEvent.setEstimatedCasualties(event.getEstimatedCasualties());
        existingEvent.setTags(event.getTags());
        existingEvent.setUpdatedAt(LocalDateTime.now());
        
        return eventRepository.save(existingEvent);
    }

    public Event assignEvent(Long eventId, Long handlerId) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        User handler = userRepository.findById(handlerId).orElse(null);
        if (handler == null) {
            throw new RuntimeException("处理人不存在");
        }
        
        event.setHandler(handler);
        event.setStatus("ASSIGNED");
        event.setUpdatedAt(LocalDateTime.now());
        
        return eventRepository.save(event);
    }




    @Override
    public Event assignEvent(Long eventId, Long handlerId, List<Long> resourceIds) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        // 指派处理人
        if (handlerId != null) {
            User handler = userRepository.findById(handlerId).orElse(null);
            if (handler == null) {
                throw new RuntimeException("处理人不存在");
            }
            
            // 检查处理人是否可用
            if (!userService.isUserAvailable(handlerId)) {
                throw new RuntimeException("处理人当前不可用，可能正在处理其他事件");
            }
            
            // 如果之前有处理人，将其状态设置为AVAILABLE
            if (event.getHandler() != null) {
                userService.updateUserStatus(event.getHandler().getId(), "AVAILABLE");
            }
            
            event.setHandler(handler);
            event.setStatus("ASSIGNED");
            event.setAssignedTime(LocalDateTime.now());
            
            // 将新处理人的状态设置为BUSY
            userService.updateUserStatus(handlerId, "BUSY");
        }
        
        // 分配资源（这里需要ResourceService支持）
        if (resourceIds != null && !resourceIds.isEmpty()) {
            // TODO: 实现资源分配逻辑
            // event.setResources(resources);
        }
        
        event.setUpdatedAt(LocalDateTime.now());
        Event savedEvent = eventRepository.save(event);
        
        // 发送通知
        sendEventNotification(savedEvent, "事件已指派给您处理", "ASSIGNMENT");
        
        return savedEvent;
    }

    @Override
    public Event updateEventProgress(Long eventId, String progress, String status) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        // 更新事件状态
        if (status != null && !status.isEmpty()) {
            event.setStatus(status);
            
            // 根据状态设置相应时间
            switch (status) {
                case "ASSIGNED":
                    event.setAssignedTime(LocalDateTime.now());
                    break;
                case "IN_PROGRESS":
                    event.setInProgressTime(LocalDateTime.now());
                    break;
                case "RESOLVED":
                    event.setResolutionTime(LocalDateTime.now());
                    // 释放处理人
                    if (event.getHandler() != null) {
                        userService.updateUserStatus(event.getHandler().getId(), "AVAILABLE");
                    }
                    // 释放资源
                    releaseResourcesForEvent(eventId);
                    break;
                case "CLOSED":
                    // 释放处理人
                    if (event.getHandler() != null) {
                        userService.updateUserStatus(event.getHandler().getId(), "AVAILABLE");
                    }
                    // 释放资源
                    releaseResourcesForEvent(eventId);
                    break;
            }
        }
        
        event.setUpdatedAt(LocalDateTime.now());
        Event savedEvent = eventRepository.save(event);
        
        // 记录进度历史
        EventResponse progressRecord = new EventResponse();
        progressRecord.setEvent(savedEvent);
        progressRecord.setDescription(progress);
        progressRecord.setResponseType("UPDATE"); // 设置响应类型
        progressRecord.setStatus(status != null ? status : savedEvent.getStatus());
        progressRecord.setResponseTime(LocalDateTime.now());
        
        // 设置响应人，如果事件没有处理人，则使用当前用户
        User responder = savedEvent.getHandler();
        if (responder == null) {
            // 如果没有处理人，使用当前登录用户作为响应人
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && !"anonymousUser".equals(authentication.getPrincipal())) {
                responder = userRepository.findByUsername(authentication.getName());
            }
        }
        progressRecord.setResponder(responder);
        
        // 设置响应者位置信息 - 从最新的EventResponse记录获取响应者位置
        List<EventResponse> recentResponses = eventResponseRepository.findByEventIdOrderByResponseTimeDesc(eventId);
        if (!recentResponses.isEmpty()) {
            EventResponse latestResponse = recentResponses.get(0);
            if (latestResponse.getLocation() != null && !latestResponse.getLocation().isEmpty()) {
                progressRecord.setLocation(latestResponse.getLocation());
            }
        }
        
        progressRecord.setCreatedAt(LocalDateTime.now());
        progressRecord.setUpdatedAt(LocalDateTime.now());
        eventResponseRepository.save(progressRecord);
        
        // 发送通知
        sendEventNotification(savedEvent, "事件进度已更新：" + progress, "PROGRESS");
        
        return savedEvent;
    }

    @Override
    public List<EventResponse> getEventProgressHistory(Long eventId) {
        return eventResponseRepository.findByEventIdOrderByResponseTimeDesc(eventId);
    }

    @Override
    public void sendEventNotification(Event event, String message, String type) {
        // 这里可以实现通知推送逻辑
        // 1. 数据库通知记录
        // 2. WebSocket推送
        // 3. 邮件/短信通知
        // 4. 系统日志
        
        System.out.println("通知: " + type + " - " + message + " (事件ID: " + event.getId() + ")");
        
        // TODO: 实现具体的通知逻辑
        // 例如：保存到通知表、发送WebSocket消息等
    }

    @Override
    public void assignResourcesToEvent(Long eventId, List<Long> resourceIds, Long assignerId) {
        Event event = findById(eventId);
        if (event == null) throw new RuntimeException("事件不存在");
        if (event.getHandler() == null) throw new RuntimeException("请先指派处理人");

        // 查询已指派的资源
        List<Long> alreadyAssigned = eventResourceRepository.findResourceIdsByEventId(eventId);
        for (Long rid : resourceIds) {
            if (alreadyAssigned.contains(rid)) continue; // 已指派跳过
            Resource res = resourceRepository.findById(rid).orElseThrow(() -> new RuntimeException("资源不存在: " + rid));
            if (!"AVAILABLE".equals(res.getStatus())) throw new RuntimeException("资源【"+res.getName()+"】不可用");
            // 新增指派关系
            EventResource er = new EventResource();
            er.setEvent(event);
            er.setResource(res);
            er.setAssignedAt(LocalDateTime.now());
            er.setAssignedBy(assignerId);
            er.setHandler(event.getHandler()); // 设置当前处理人
            er.setStatus("ASSIGNED");
            eventResourceRepository.save(er);
            // 资源状态变为IN_USE
            res.setStatus("IN_USE");
            resourceRepository.save(res);
        }

        // 如果成功分配了至少一个资源，则之前设置的状态为ASSIGNED是合理的
        // 但是不应该在这里直接变为IN_PROGRESS
        // IN_PROGRESS状态应该由终端用户实际开始执行任务时触发
        /*
        if (!resourceIds.isEmpty() && !"IN_PROGRESS".equals(event.getStatus())) {
            event.setStatus("IN_PROGRESS");
            event.setInProgressTime(LocalDateTime.now());
            eventRepository.save(event);
        }
        */
    }

    @Override
    public void removeResourceFromEvent(Long eventId, Long resourceId) {
        Event event = findById(eventId);
        if (event == null) throw new RuntimeException("事件不存在");
        
        Resource resource = resourceRepository.findById(resourceId).orElse(null);
        if (resource == null) throw new RuntimeException("资源不存在");
        
        // 查找event_resources表中的关联记录
        EventResource er = eventResourceRepository.findByEventAndResource(event, resource);
        if (er != null) {
            // 不删除记录，而是更新状态
            er.setStatus("REMOVED");
            er.setNotes("手动移除 - " + LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            eventResourceRepository.save(er);
            
            // 资源状态改为AVAILABLE
            resource.setStatus("AVAILABLE");
            resourceRepository.save(resource);
        } else {
            throw new RuntimeException("该单位未指派到本事件");
        }
    }

    @Override
    public List<Resource> findResourcesByEventId(Long eventId) {
        List<Long> resourceIds = eventResourceRepository.findResourceIdsByEventId(eventId);
        if (resourceIds.isEmpty()) {
            return java.util.Collections.emptyList();
        }
        return resourceRepository.findAllById(resourceIds);
    }

    @Override
    public List<EventResource> getResourceHistoryByEventId(Long eventId) {
        return eventResourceRepository.findByEventId(eventId);
    }

    // 终端用户操作相关方法实现

    /**
     * 检查用户是否有权操作此事件
     * 权限要求：用户是事件的主处理人，或者是事件中任一已分配资源的处理人
     * @param event 事件对象
     * @param userId 用户ID
     * @return boolean
     */
    private boolean isUserAuthorizedForEvent(Event event, Long userId) {
        if (event == null || userId == null) {
            return false;
        }
        // 检查是否为主处理人
        if (event.getHandler() != null && userId.equals(event.getHandler().getId())) {
            return true;
        }
        // 检查是否为资源处理人
        List<EventResource> resources = eventResourceRepository.findByEventIdAndStatusIn(event.getId(), List.of("ASSIGNED", "IN_USE"));
        return resources.stream().anyMatch(r -> r.getHandler() != null && userId.equals(r.getHandler().getId()));
    }

    @Override
    public Event acceptEvent(Long eventId, Long responderId) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        if (!isUserAuthorizedForEvent(event, responderId)) {
            throw new RuntimeException("无权操作此事件");
        }
        
        event.setResponderStatus("ACCEPTED");
        event.setStatus("ACCEPTED"); // 同时更新主状态字段
        event.setAcceptedTime(LocalDateTime.now());
        event.setUpdatedAt(LocalDateTime.now());
        
        Event savedEvent = eventRepository.save(event);
        
        // 记录进度
        updateEventProgress(eventId, "响应人员已接受任务", "ACCEPTED");
        
        return savedEvent;
    }

    @Override
    public Event startEnRoute(Long eventId, Long responderId, Double latitude, Double longitude) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        if (!isUserAuthorizedForEvent(event, responderId)) {
            throw new RuntimeException("无权操作此事件");
        }
        
        event.setResponderStatus("EN_ROUTE");
        event.setStatus("EN_ROUTE"); // 同时更新主状态字段
        event.setUpdatedAt(LocalDateTime.now());
        
        // 如果提供了位置信息，则保存位置
        if (latitude != null && longitude != null && isValidCoordinates(latitude, longitude)) {
            // 创建新的EventResponse记录来保存响应者位置
            EventResponse locationResponse = new EventResponse();
            locationResponse.setEvent(event);
            locationResponse.setResponder(userRepository.findById(responderId).orElse(null));
            locationResponse.setResponseType("LOCATION_UPDATE");
            locationResponse.setDescription("响应者位置更新");
            locationResponse.setStatus("COMPLETED");
            locationResponse.setResponseTime(LocalDateTime.now());
            locationResponse.setLocation(longitude + "," + latitude);
            locationResponse.setCreatedAt(LocalDateTime.now());
            locationResponse.setUpdatedAt(LocalDateTime.now());
            
            eventResponseRepository.save(locationResponse);
            
            // 更新事件的最后位置更新时间
            event.setLastLocationUpdate(LocalDateTime.now());
        }
        
        Event savedEvent = eventRepository.save(event);
        updateEventProgress(eventId, "响应人员已出发前往现场", "EN_ROUTE");
        return savedEvent;
    }

    @Override
    public Event arriveAtScene(Long eventId, Long responderId, Double latitude, Double longitude) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        if (!isUserAuthorizedForEvent(event, responderId)) {
            throw new RuntimeException("无权操作此事件");
        }
        
        event.setResponderStatus("ARRIVED");
        event.setStatus("ARRIVED"); // 同时更新主状态字段
        event.setArrivedTime(LocalDateTime.now());
        event.setUpdatedAt(LocalDateTime.now());
        
        // 如果提供了位置信息，则保存位置
        if (latitude != null && longitude != null && isValidCoordinates(latitude, longitude)) {
            // 创建新的EventResponse记录来保存响应者位置
            EventResponse locationResponse = new EventResponse();
            locationResponse.setEvent(event);
            locationResponse.setResponder(userRepository.findById(responderId).orElse(null));
            locationResponse.setResponseType("LOCATION_UPDATE");
            locationResponse.setDescription("响应者位置更新");
            locationResponse.setStatus("COMPLETED");
            locationResponse.setResponseTime(LocalDateTime.now());
            locationResponse.setLocation(longitude + "," + latitude);
            locationResponse.setCreatedAt(LocalDateTime.now());
            locationResponse.setUpdatedAt(LocalDateTime.now());
            
            eventResponseRepository.save(locationResponse);
            
            // 更新事件的最后位置更新时间
            event.setLastLocationUpdate(LocalDateTime.now());
        }
        
        Event savedEvent = eventRepository.save(event);
        updateEventProgress(eventId, "响应人员已到达现场", "ARRIVED");
        return savedEvent;
    }

    @Override
    public Event startProcessing(Long eventId, Long responderId) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        if (!isUserAuthorizedForEvent(event, responderId)) {
            throw new RuntimeException("无权操作此事件");
        }
        
        event.setResponderStatus("IN_PROGRESS");
        event.setStatus("IN_PROGRESS"); // 同时更新主状态字段
        event.setInProgressTime(LocalDateTime.now());
        event.setUpdatedAt(LocalDateTime.now());
        
        Event savedEvent = eventRepository.save(event);
        
        // 记录进度
        updateEventProgress(eventId, "现场处置进行中", "IN_PROGRESS");
        
        return savedEvent;
    }

    @Override
    public Event completeEvent(Long eventId, Long responderId, String completionNotes) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        if (!isUserAuthorizedForEvent(event, responderId)) {
            throw new RuntimeException("无权操作此事件");
        }
        
        event.setResponderStatus("COMPLETED");
        event.setStatus("COMPLETED"); // 同时更新主状态字段
        event.setCompletedTime(LocalDateTime.now());
        event.setResponderNotes(completionNotes);
        event.setUpdatedAt(LocalDateTime.now());
        
        // 计算处置时间和总时间
        if (event.getArrivedTime() != null) {
            event.setProcessingTimeMinutes(java.time.Duration.between(event.getArrivedTime(), event.getCompletedTime()).toMinutes());
        }
        
        if (event.getAssignedTime() != null) {
            event.setTotalTimeMinutes(java.time.Duration.between(event.getAssignedTime(), event.getCompletedTime()).toMinutes());
        }
        
        Event savedEvent = eventRepository.save(event);
        
        // 记录进度
        updateEventProgress(eventId, "现场处置已完成：" + completionNotes, "COMPLETED");
        
        // 释放用户状态为可用（事件完成后不再设置返回中状态）
        userService.updateUserStatus(responderId, "AVAILABLE");
        
        // 释放事件关联的资源
        releaseResourcesForEvent(eventId);
        
        return savedEvent;
    }

    @Override
    public Event startReturning(Long eventId, Long responderId) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        if (!isUserAuthorizedForEvent(event, responderId)) {
            throw new RuntimeException("无权操作此事件");
        }
        
        event.setResponderStatus("RETURNING");
        event.setStatus("RETURNING"); // 同时更新主状态字段
        event.setUpdatedAt(LocalDateTime.now());
        
        Event savedEvent = eventRepository.save(event);
        
        // 记录进度
        updateEventProgress(eventId, "响应人员正在返程", "RETURNING");
        
        // 更新用户状态为可用
        userService.updateUserStatus(responderId, "AVAILABLE");
        
        return savedEvent;
    }

    @Override
    public Event updateLocation(Long eventId, Long responderId, Double latitude, Double longitude) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        if (!isUserAuthorizedForEvent(event, responderId)) {
            throw new RuntimeException("无权操作此事件");
        }
        
        // 验证坐标
        if (!isValidCoordinates(latitude, longitude)) {
            throw new RuntimeException("无效的坐标值：纬度范围-90到90，经度范围-180到180");
        }
        
        // 创建新的EventResponse记录来保存响应者位置
        EventResponse locationResponse = new EventResponse();
        locationResponse.setEvent(event);
        locationResponse.setResponder(userRepository.findById(responderId).orElse(null));
        locationResponse.setResponseType("LOCATION_UPDATE");
        locationResponse.setDescription("响应者位置更新");
        locationResponse.setStatus("COMPLETED");
        locationResponse.setResponseTime(LocalDateTime.now());
        locationResponse.setLocation(longitude + "," + latitude); // 保存响应者位置到EventResponse.location
        locationResponse.setCreatedAt(LocalDateTime.now());
        locationResponse.setUpdatedAt(LocalDateTime.now());
        
        eventResponseRepository.save(locationResponse);
        
        // 更新事件的最后位置更新时间
        event.setLastLocationUpdate(LocalDateTime.now());
        event.setUpdatedAt(LocalDateTime.now());
        
        return eventRepository.save(event);
    }

    @Override
    public Event updateSafetyStatus(Long eventId, Long responderId, String safetyStatus) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        if (!isUserAuthorizedForEvent(event, responderId)) {
            throw new RuntimeException("无权操作此事件");
        }
        
        event.setSafetyStatus(safetyStatus);
        event.setLastSafetyReport(LocalDateTime.now());
        event.setUpdatedAt(LocalDateTime.now());
        
        Event savedEvent = eventRepository.save(event);
        
        // 如果是SOS状态，记录紧急进度
        if ("SOS".equals(safetyStatus)) {
            updateEventProgress(eventId, "响应人员发送SOS紧急求助信号", "IN_PROGRESS");
        }
        
        return savedEvent;
    }

    @Override
    public Event requestSupport(Long eventId, Long responderId, String supportType, String description) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        if (!isUserAuthorizedForEvent(event, responderId)) {
            throw new RuntimeException("无权操作此事件");
        }
        
        event.setSupportRequested(true);
        event.setSupportType(supportType);
        event.setSupportRequestTime(LocalDateTime.now());
        event.setUpdatedAt(LocalDateTime.now());
        
        Event savedEvent = eventRepository.save(event);
        
        // 记录进度
        updateEventProgress(eventId, "请求" + supportType + "支援：" + description, "IN_PROGRESS");
        
        return savedEvent;
    }

    @Override
    public Event cancelSupportRequest(Long eventId, Long responderId) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        if (!isUserAuthorizedForEvent(event, responderId)) {
            throw new RuntimeException("无权操作此事件");
        }
        
        event.setSupportRequested(false);
        event.setSupportType(null);
        event.setSupportRequestTime(null);
        event.setUpdatedAt(LocalDateTime.now());
        
        Event savedEvent = eventRepository.save(event);
        
        // 记录进度
        updateEventProgress(eventId, "取消支援请求", "IN_PROGRESS");
        
        return savedEvent;
    }

    @Override
    public Event sendSOS(Long eventId, Long responderId, String message) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        if (!isUserAuthorizedForEvent(event, responderId)) {
            throw new RuntimeException("无权操作此事件");
        }
        
        event.setSafetyStatus("SOS");
        event.setLastSafetyReport(LocalDateTime.now());
        event.setUpdatedAt(LocalDateTime.now());
        
        Event savedEvent = eventRepository.save(event);
        
        // 记录进度
        updateEventProgress(eventId, "SOS紧急求助：" + message, "IN_PROGRESS");
        
        return savedEvent;
    }

    @Override
    public List<Event> getUserEvents(Long responderId) {
        return eventRepository.findByHandlerIdOrderByCreatedAtDesc(responderId);
    }

    @Override
    public List<Event> getUserActiveEvents(Long responderId) {
        List<String> activeStatuses = Arrays.asList("ASSIGNED", "IN_PROGRESS");
        return eventRepository.findByHandlerIdAndStatusInOrderByCreatedAtDesc(responderId, activeStatuses);
    }

    @Override
    public Optional<Event> getCurrentActiveEvent(Long responderId) {
        // 1. 查找用户作为主处理人的活动事件（排除已完成的事件）
        List<String> activeStatuses = Arrays.asList("ASSIGNED", "ACCEPTED", "EN_ROUTE", "ARRIVED", "IN_PROGRESS");
        List<Event> activeEventsAsMainHandler = eventRepository.findByHandlerIdAndStatusInOrderByCreatedAtDesc(responderId, activeStatuses);

        // 2. 查找用户作为资源处理人的活动事件（排除已完成的事件）
        List<Event> activeEventsAsResourceHandler = eventRepository.findActiveEventsByResourceHandlerId(responderId);

        // 3. 合并并去重
        Set<Event> allActiveEvents = new HashSet<>(activeEventsAsMainHandler);
        allActiveEvents.addAll(activeEventsAsResourceHandler);

        // 4. 按开始时间倒序排序，并返回最新的一个
        return allActiveEvents.stream()
                .sorted(Comparator.comparing(Event::getStartTime).reversed())
                .findFirst();
    }

    @Override
    public List<Event> getEventsNeedingAttention() {
        return eventRepository.findBySafetyStatusOrSupportRequested("SOS", true);
    }

    @Override
    public List<Event> getOverdueEvents() {
        LocalDateTime timeout = LocalDateTime.now().minusMinutes(5); // 5分钟超时
        return eventRepository.findByStatusAndAssignedTimeBefore("ASSIGNED", timeout);
    }

    @Override
    public Map<String, Object> getUserEventStatistics(Long responderId) {
        Map<String, Object> stats = new HashMap<>();
        
        List<Event> allEvents = getUserEvents(responderId);
        long totalEvents = allEvents.size();
        long completedEvents = allEvents.stream().filter(e -> "RESOLVED".equals(e.getStatus()) || "CLOSED".equals(e.getStatus())).count();
        long activeEvents = getUserActiveEvents(responderId).size();
        
        // 计算平均响应时间
        double avgResponseTime = allEvents.stream()
            .filter(e -> e.getResponseTimeMinutes() != null)
            .mapToLong(Event::getResponseTimeMinutes)
            .average()
            .orElse(0.0);
        
        // 计算平均处置时间
        double avgProcessingTime = allEvents.stream()
            .filter(e -> e.getProcessingTimeMinutes() != null)
            .mapToLong(Event::getProcessingTimeMinutes)
            .average()
            .orElse(0.0);
        
        stats.put("totalEvents", totalEvents);
        stats.put("completedEvents", completedEvents);
        stats.put("activeEvents", activeEvents);
        stats.put("avgResponseTime", avgResponseTime);
        stats.put("avgProcessingTime", avgProcessingTime);
        
        return stats;
    }

    @Override
    public Map<String, Object> getEventPerformanceStatistics(Long eventId) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("responseTime", event.getResponseTimeMinutes());
        stats.put("processingTime", event.getProcessingTimeMinutes());
        stats.put("totalTime", event.getTotalTimeMinutes());
        stats.put("assignedTime", event.getAssignedTime());
        stats.put("arrivedTime", event.getArrivedTime());
        stats.put("completedTime", event.getCompletedTime());
        
        return stats;
    }

    @Override
    public List<Map<String, Object>> getEventTimeline(Long eventId) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        List<Map<String, Object>> timeline = new ArrayList<>();
        
        // 事件创建
        if (event.getCreatedAt() != null) {
            Map<String, Object> eventItem = new HashMap<>();
            eventItem.put("time", event.getCreatedAt());
            eventItem.put("type", "EVENT_CREATED");
            eventItem.put("description", "事件创建");
            timeline.add(eventItem);
        }
        
        // 任务分配
        if (event.getAssignedTime() != null) {
            Map<String, Object> eventItem = new HashMap<>();
            eventItem.put("time", event.getAssignedTime());
            eventItem.put("type", "TASK_ASSIGNED");
            eventItem.put("description", "已指派");
            timeline.add(eventItem);
        }
        
        // 任务接受
        if (event.getAcceptedTime() != null) {
            Map<String, Object> eventItem = new HashMap<>();
            eventItem.put("time", event.getAcceptedTime());
            eventItem.put("type", "TASK_ACCEPTED");
            eventItem.put("description", "已接受");
            timeline.add(eventItem);
        }
        
        // 开始前往
        if (event.getEnRouteTime() != null) {
            Map<String, Object> eventItem = new HashMap<>();
            eventItem.put("time", event.getEnRouteTime());
            eventItem.put("type", "EN_ROUTE");
            eventItem.put("description", "正在前往");
            timeline.add(eventItem);
        }
        
        // 到达现场
        if (event.getArrivedTime() != null) {
            Map<String, Object> eventItem = new HashMap<>();
            eventItem.put("time", event.getArrivedTime());
            eventItem.put("type", "ARRIVED");
            eventItem.put("description", "到达现场");
            timeline.add(eventItem);
        }
        
        // 开始处理
        if (event.getInProgressTime() != null) {
            Map<String, Object> eventItem = new HashMap<>();
            eventItem.put("time", event.getInProgressTime());
            eventItem.put("type", "IN_PROGRESS");
            eventItem.put("description", "开始处理");
            timeline.add(eventItem);
        }
        
        // 任务完成
        if (event.getCompletedTime() != null) {
            Map<String, Object> eventItem = new HashMap<>();
            eventItem.put("time", event.getCompletedTime());
            eventItem.put("type", "TASK_COMPLETED");
            eventItem.put("description", "完成任务");
            timeline.add(eventItem);
        }
        
        // 开始返程
        if ("RETURNING".equals(event.getResponderStatus())) {
            Map<String, Object> eventItem = new HashMap<>();
            eventItem.put("time", event.getUpdatedAt());
            eventItem.put("type", "RETURNING");
            eventItem.put("description", "开始返程");
            timeline.add(eventItem);
        }
        
        // 按时间排序
        timeline.sort((a, b) -> ((LocalDateTime) a.get("time")).compareTo((LocalDateTime) b.get("time")));
        
        return timeline;
    }

    @Override
    public Map<String, Object> getEventResponseStatistics(Long eventId) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("responseTime", event.getResponseTimeMinutes());
        stats.put("processingTime", event.getProcessingTimeMinutes());
        stats.put("totalTime", event.getTotalTimeMinutes());
        stats.put("hasEmergency", event.isEmergency());
        stats.put("needsAttention", event.needsAttention());
        stats.put("safetyStatus", event.getSafetyStatus());
        stats.put("supportRequested", event.getSupportRequested());
        
        return stats;
    }

    @Override
    public boolean canAutoCloseEvent(Long eventId) {
        Event event = findById(eventId);
        if (event == null) return false;
        
        return "COMPLETED".equals(event.getResponderStatus()) || "RETURNING".equals(event.getResponderStatus());
    }

    @Override
    public void autoCloseEvent(Long eventId) {
        if (canAutoCloseEvent(eventId)) {
            updateEventProgress(eventId, "所有响应任务已完成，事件自动结案", "CLOSED");
        }
    }

    @Override
    public Event reassignEvent(Long eventId, Long newResponderId, String reason) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }
        
        User newResponder = userRepository.findById(newResponderId)
            .orElseThrow(() -> new RuntimeException("新响应者不存在"));
        
        // 释放原响应者
        User oldResponder = event.getHandler();
        if (oldResponder != null) {
            userService.updateUserStatus(oldResponder.getId(), "AVAILABLE");
        }
        
        event.setHandler(newResponder);
        event.setStatus("ASSIGNED");
        event.setResponderStatus("ASSIGNED");
        event.setAssignedTime(LocalDateTime.now());
        event.setUpdatedAt(LocalDateTime.now());
        
        // 更新新响应者状态为忙碌
        userService.updateUserStatus(newResponderId, "BUSY");
        
        Event savedEvent = eventRepository.save(event);
        
        // 记录进度
        updateEventProgress(eventId, "任务重新分配：" + reason, "ASSIGNED");
        
        return savedEvent;
    }

    @Override
    public Event escalateEvent(Long eventId, String escalationReason) {
        Event event = findById(eventId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }

        event.setUpdatedAt(LocalDateTime.now());
        
        Event savedEvent = eventRepository.save(event);
        
        // 记录进度
        updateEventProgress(eventId, "事件升级：" + escalationReason, "IN_PROGRESS");
        
        return savedEvent;
    }

    @Override
    public List<Event> batchUpdateStatus(List<Long> eventIds, String status) {
        List<Event> events = eventRepository.findAllById(eventIds);
        List<Event> updatedEvents = new ArrayList<>();
        
        for (Event event : events) {
            event.setStatus(status);
            event.setUpdatedAt(LocalDateTime.now());
            Event savedEvent = eventRepository.save(event);
            updatedEvents.add(savedEvent);
        }
        
        return updatedEvents;
    }

    @Override
    public List<Event> getEventHistory(Long responderId, LocalDateTime start, LocalDateTime end) {
        return eventRepository.findByHandlerIdAndCreatedAtBetweenOrderByCreatedAtDesc(responderId, start, end);
    }

    @Override
    public byte[] exportEventReport(Long eventId) {
        // TODO: 实现事件报告导出功能
        return new byte[0];
    }

    @Override
    public byte[] exportUserEventHistory(Long responderId, LocalDateTime start, LocalDateTime end) {
        // TODO: 实现用户事件历史导出功能
        return new byte[0];
    }

    @Override
    public List<Event> getUserEventHistory(Long responderId) {
        // 获取用户所有已完成、已解决、已关闭的事件
        List<String> completedStatuses = Arrays.asList("COMPLETED", "CLOSED", "RESOLVED");
        return eventRepository.findByHandlerIdAndStatusInOrderByCompletedTimeDesc(responderId, completedStatuses);
    }

    @Override
    public List<Event> getUserCompletedEvents(Long responderId) {
        // 获取用户所有已完成的事件
        return eventRepository.findByHandlerIdAndStatusOrderByCompletedTimeDesc(responderId, "COMPLETED");
    }

    @Override
    public List<Event> getUserTodayCompletedEvents(Long responderId) {
        // 获取用户今日已完成的事件
        LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime todayEnd = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59).withNano(999999999);
        
        // 查询今日完成的事件（包括已完成、已解决、已关闭）
        List<String> completedStatuses = Arrays.asList("COMPLETED", "CLOSED", "RESOLVED");
        return eventRepository.findByHandlerIdAndStatusInAndCompletedTimeBetweenOrderByCompletedTimeDesc(
            responderId, completedStatuses, todayStart, todayEnd);
    }

    // 坐标验证方法
    private boolean isValidCoordinates(Double latitude, Double longitude) {
        if (latitude == null || longitude == null) {
            return false;
        }
        // 纬度范围：-90 到 90
        if (latitude < -90 || latitude > 90) {
            return false;
        }
        // 经度范围：-180 到 180
        if (longitude < -180 || longitude > 180) {
            return false;
        }
        return true;
    }
    
    // 检查事件是否有有效坐标
    public boolean hasValidCoordinates(Long eventId) {
        Event event = findById(eventId);
        if (event == null) {
            return false;
        }
        return isValidCoordinates(event.getCurrentLatitude(), event.getCurrentLongitude());
    }

    @Override
    public List<EventResource> findCurrentEventResources(Long eventId) {
        return eventResourceRepository.findByEventIdAndStatusIn(eventId, List.of("ASSIGNED", "IN_USE"));
    }

    // ========== 统计分析相关方法实现 ==========

    @Override
    public Map<String, Object> getEventOverviewStatistics(LocalDateTime start, LocalDateTime end) {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取时间范围内的事件
        List<Event> events = eventRepository.findByStartTimeBetween(start, end);
        
        // 事件总量
        stats.put("totalEvents", events.size());
        
        // 事件状态分布
        Map<String, Long> statusDistribution = events.stream()
            .collect(Collectors.groupingBy(Event::getStatus, Collectors.counting()));
        stats.put("statusDistribution", statusDistribution);
        
        // 事件类型分布
        Map<String, Long> typeDistribution = events.stream()
            .filter(e -> e.getEventType() != null)
            .collect(Collectors.groupingBy(e -> e.getEventType().getName(), Collectors.counting()));
        stats.put("typeDistribution", typeDistribution);
        
        // 事件严重程度分布
        Map<String, Long> severityDistribution = events.stream()
            .collect(Collectors.groupingBy(Event::getSeverity, Collectors.counting()));
        stats.put("severityDistribution", severityDistribution);
        
        // 事件优先级分布
        Map<String, Long> priorityDistribution = events.stream()
            .collect(Collectors.groupingBy(Event::getPriority, Collectors.counting()));
        stats.put("priorityDistribution", priorityDistribution);
        
        // 事件来源分布
        Map<String, Long> sourceDistribution = events.stream()
            .collect(Collectors.groupingBy(Event::getSource, Collectors.counting()));
        stats.put("sourceDistribution", sourceDistribution);
        
        // 平均每日事件量
        long daysBetween = java.time.Duration.between(start, end).toDays();
        if (daysBetween > 0) {
            stats.put("averageDailyEvents", (double) events.size() / daysBetween);
        } else {
            stats.put("averageDailyEvents", 0.0);
        }
        
        return stats;
    }

    @Override
    public Map<String, Object> getEventTrendStatistics(LocalDateTime start, LocalDateTime end, String period) {
        Map<String, Object> stats = new HashMap<>();
        List<Event> events = eventRepository.findByStartTimeBetween(start, end);
        
        Map<String, List<Event>> groupedEvents = new HashMap<>();
        
        switch (period.toLowerCase()) {
            case "hourly":
                // 按小时分组
                for (Event event : events) {
                    String hourKey = event.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:00"));
                    groupedEvents.computeIfAbsent(hourKey, k -> new ArrayList<>()).add(event);
                }
                break;
            case "daily":
                // 按天分组
                for (Event event : events) {
                    String dayKey = event.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    groupedEvents.computeIfAbsent(dayKey, k -> new ArrayList<>()).add(event);
                }
                break;
            case "weekly":
                // 按周分组
                for (Event event : events) {
                    String weekKey = event.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-'W'ww"));
                    groupedEvents.computeIfAbsent(weekKey, k -> new ArrayList<>()).add(event);
                }
                break;
            case "monthly":
                // 按月分组
                for (Event event : events) {
                    String monthKey = event.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM"));
                    groupedEvents.computeIfAbsent(monthKey, k -> new ArrayList<>()).add(event);
                }
                break;
            default:
                // 默认按天分组
                for (Event event : events) {
                    String dayKey = event.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    groupedEvents.computeIfAbsent(dayKey, k -> new ArrayList<>()).add(event);
                }
        }
        
        // 转换为时间序列数据
        List<Map<String, Object>> timeSeriesData = new ArrayList<>();
        for (Map.Entry<String, List<Event>> entry : groupedEvents.entrySet()) {
            Map<String, Object> dataPoint = new HashMap<>();
            dataPoint.put("time", entry.getKey());
            dataPoint.put("count", entry.getValue().size());
            
            // 按状态统计
            Map<String, Long> statusCounts = entry.getValue().stream()
                .collect(Collectors.groupingBy(Event::getStatus, Collectors.counting()));
            dataPoint.put("statusBreakdown", statusCounts);
            
            timeSeriesData.add(dataPoint);
        }
        
        // 按时间排序
        timeSeriesData.sort((a, b) -> ((String) a.get("time")).compareTo((String) b.get("time")));
        
        stats.put("timeSeriesData", timeSeriesData);
        stats.put("period", period);
        
        return stats;
    }

    @Override
    public Map<String, Object> getResponseEfficiencyStatistics(LocalDateTime start, LocalDateTime end) {
        Map<String, Object> stats = new HashMap<>();
        List<Event> events = eventRepository.findByStartTimeBetween(start, end);
        
        // 过滤有响应时间数据的事件
        List<Event> eventsWithResponseTime = events.stream()
            .filter(e -> e.getResponseTimeMinutes() != null)
            .collect(Collectors.toList());
        
        List<Event> eventsWithProcessingTime = events.stream()
            .filter(e -> e.getProcessingTimeMinutes() != null)
            .collect(Collectors.toList());
        
        // 平均响应时间
        double avgResponseTime = eventsWithResponseTime.stream()
            .mapToLong(Event::getResponseTimeMinutes)
            .average()
            .orElse(0.0);
        stats.put("averageResponseTime", avgResponseTime);
        
        // 平均处置时间
        double avgProcessingTime = eventsWithProcessingTime.stream()
            .mapToLong(Event::getProcessingTimeMinutes)
            .average()
            .orElse(0.0);
        stats.put("averageProcessingTime", avgProcessingTime);
        
        // 响应时间达标率（假设目标为15分钟）
        long targetResponseTime = 15; // 分钟
        long responseTimeCompliant = eventsWithResponseTime.stream()
            .filter(e -> e.getResponseTimeMinutes() <= targetResponseTime)
            .count();
        double responseTimeComplianceRate = eventsWithResponseTime.size() > 0 ? 
            (double) responseTimeCompliant / eventsWithResponseTime.size() * 100 : 0.0;
        stats.put("responseTimeComplianceRate", responseTimeComplianceRate);
        
        // 各环节时间分布
        Map<String, Object> timeDistribution = new HashMap<>();
        timeDistribution.put("avgResponseTime", avgResponseTime);
        timeDistribution.put("avgProcessingTime", avgProcessingTime);
        timeDistribution.put("avgTotalTime", avgResponseTime + avgProcessingTime);
        stats.put("timeDistribution", timeDistribution);
        
        // 按事件类型统计响应时间
        Map<String, Double> responseTimeByType = eventsWithResponseTime.stream()
            .filter(e -> e.getEventType() != null)
            .collect(Collectors.groupingBy(
                e -> e.getEventType().getName(),
                Collectors.averagingLong(Event::getResponseTimeMinutes)
            ));
        stats.put("responseTimeByType", responseTimeByType);
        
        // 按严重程度统计响应时间
        Map<String, Double> responseTimeBySeverity = eventsWithResponseTime.stream()
            .collect(Collectors.groupingBy(
                Event::getSeverity,
                Collectors.averagingLong(Event::getResponseTimeMinutes)
            ));
        stats.put("responseTimeBySeverity", responseTimeBySeverity);
        
        return stats;
    }

    @Override
    public Map<String, Object> getGeographicDistributionStatistics(LocalDateTime start, LocalDateTime end) {
        Map<String, Object> stats = new HashMap<>();
        List<Event> events = eventRepository.findByStartTimeBetween(start, end);
        
        // 地理坐标数据
        List<Map<String, Object>> coordinates = new ArrayList<>();
        
        for (Event event : events) {
            Double latitude = null;
            Double longitude = null;
            
            // 优先使用currentLatitude和currentLongitude
            if (event.getCurrentLatitude() != null && event.getCurrentLongitude() != null) {
                latitude = event.getCurrentLatitude();
                longitude = event.getCurrentLongitude();
            } 
            // 如果没有GPS坐标，尝试解析location字段中的坐标
            else if (event.getLocation() != null && !event.getLocation().trim().isEmpty()) {
                String location = event.getLocation().trim();
                // 检查是否是坐标格式 (lng,lat)
                if (location.matches("^-?\\d+\\.\\d+,-?\\d+\\.\\d+$")) {
                    String[] parts = location.split(",");
                    try {
                        longitude = Double.parseDouble(parts[0]);
                        latitude = Double.parseDouble(parts[1]);
                    } catch (NumberFormatException e) {
                        // 解析失败，跳过这个事件
                        continue;
                    }
                }
            }
            
            // 如果有有效坐标，添加到结果中
            if (latitude != null && longitude != null) {
                Map<String, Object> coord = new HashMap<>();
                coord.put("latitude", latitude);
                coord.put("longitude", longitude);
                coord.put("eventId", event.getId());
                coord.put("title", event.getTitle());
                coord.put("status", event.getStatus());
                coord.put("severity", event.getSeverity());
                coord.put("eventType", event.getEventType() != null ? event.getEventType().getName() : "未知");
                coordinates.add(coord);
            }
        }
        
        stats.put("coordinates", coordinates);
        
        // 按区域统计（简化版本，按经纬度范围分组）
        Map<String, Long> areaDistribution = new HashMap<>();
        for (Map<String, Object> coord : coordinates) {
            Double lat = (Double) coord.get("latitude");
            Double lng = (Double) coord.get("longitude");
            // 简化的区域划分（每0.1度为一个区域）
            String areaKey = String.format("%.1f,%.1f", 
                Math.floor(lat * 10) / 10,
                Math.floor(lng * 10) / 10);
            areaDistribution.merge(areaKey, 1L, Long::sum);
        }
        stats.put("areaDistribution", areaDistribution);
        
        // 热点区域（事件数量最多的区域）
        List<Map.Entry<String, Long>> hotSpots = areaDistribution.entrySet().stream()
            .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
            .limit(10)
            .collect(Collectors.toList());
        stats.put("hotSpots", hotSpots);
        
        return stats;
    }

    @Override
    public String getLatestResponderLocation(Long eventId) {
        List<EventResponse> locationResponses = eventResponseRepository.findByEventIdAndResponseTypeOrderByResponseTimeDesc(eventId, "LOCATION_UPDATE");
        if (!locationResponses.isEmpty()) {
            return locationResponses.get(0).getLocation();
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> getAllResponderLocations(Long eventId) {
        List<EventResponse> locationResponses = eventResponseRepository.findByEventIdAndResponseTypeOrderByResponseTimeDesc(eventId, "LOCATION_UPDATE");
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 按响应者分组，获取每个响应者的最新位置
        Map<Long, EventResponse> latestByResponder = new HashMap<>();
        
        for (EventResponse response : locationResponses) {
            if (response.getResponder() != null && response.getLocation() != null) {
                Long responderId = response.getResponder().getId();
                // 只保留每个响应者的最新位置
                if (!latestByResponder.containsKey(responderId)) {
                    latestByResponder.put(responderId, response);
                }
            }
        }
        
        // 转换为返回格式
        for (EventResponse response : latestByResponder.values()) {
            Map<String, Object> locationInfo = new HashMap<>();
            locationInfo.put("responderId", response.getResponder().getId());
            locationInfo.put("responderName", response.getResponder().getRealName());
            locationInfo.put("responderUsername", response.getResponder().getUsername());
            locationInfo.put("location", response.getLocation());
            locationInfo.put("updateTime", response.getResponseTime());
            result.add(locationInfo);
        }
        
        return result;
    }
} 